import "../../Fastfile"

default_platform(:ios)


platform :ios do
  # Authenticate with Apple Store
  private_lane :authenticate_apple_store do
    app_store_connect_api_key(
      key_id: ENV["ASC_KEY_ID"],
      issuer_id: ENV["ASC_ISSUER_ID"],
      key_content: ENV["ASC_KEY_P8_BASE64"],
      is_key_content_base64: true,
      in_house: false
    )

  end

  # Build iOS app
  lane :build_ipa do
    verify_env(envs: [
      "ASC_KEY_ID",
      "ASC_ISSUER_ID",
      "ASC_KEY_P8_BASE64",
      "APP_BUNDLE_ID",
      "MATCH_PASSWORD",
      "MATCH_GIT_BASIC_AUTHORIZATION",
    ])

    authenticate_apple_store

    # Sync certificates and profiles using match
    UI.message("Syncing certificates and profiles")


    # get_certificates
    # get_provisioning_profile(app_identifier: "com.anxcye.anxReader")
    # get_provisioning_profile(app_identifier: "com.anxcye.anxReader.shareExtension")
  
    if is_ci
      create_keychain(
        name: "fastlane_tmp_keychain",
        password: "temp_password",
        default_keychain: true,
        unlock: true,
        timeout: 3600,
        add_to_search_list: true
      )
    end
    
    sync_code_signing(
      type: "appstore",
      readonly: is_ci,
      keychain_name: is_ci ? "fastlane_tmp_keychain" : "login.keychain",
      keychain_password: is_ci ? "temp_password" : nil,
    )
    commit = last_git_commit
    puts "*** Starting iOS release for commit(#{commit[:abbreviated_commit_hash]}) ***"
    
    sh_on_root(command: "which pod && which ruby")

  # if is_ci
  #   UI.message("CI Debug: Checking keychain status...")
  #   sh_on_root(command: "security list-keychains")
  #   sh_on_root(command: "security default-keychain")
    
  #   UI.message("CI Debug: Checking provisioning profiles...")
  #   sh_on_root(command: "ls -la ~/Library/MobileDevice/Provisioning\\ Profiles/ || echo 'Provisioning profiles directory not found'")
    
  #   UI.message("CI Debug: Checking certificates in keychain...")
  #   sh_on_root(command: "security find-certificate -a -p | grep 'BEGIN CERTIFICATE' | wc -l")
  # end

    # # Verify certificates are available
    # UI.message("Checking available certificates...")
    # sh_on_root(command: "security find-identity -v -p codesigning")

    fetch_dependencies
    
    sh_on_root(command: "flutter build ipa --release --dart-define=isAppStore=true")
    
    build_app(
      skip_build_archive: true,
      archive_path: "../build/ios/archive/Runner.xcarchive",
      export_method: "app-store",
      export_options: {
        teamID: "28W956D5K8",
        provisioningProfiles: {
          "com.anxcye.anxReader" => "match AppStore com.anxcye.anxReader",
          "com.anxcye.anxReader.shareExtension" => "match AppStore com.anxcye.anxReader.shareExtension"
        }
      }
    )
  end


  desc "Release a new build to Apple Store"
  lane :release_app_store do |options|

    build_ipa

    upload_to_testflight(
      skip_waiting_for_build_processing: false
    )
  end
  
  # This is a work in progress, requiring ad-hoc export method
  # desc "Release to Play Store using Firebase App Distribution"
  # lane :release_to_firebase do |options|
  #   begin
  #     build_ipa

  #     firebase_app_distribution(
  #       app: ENV["FIREBASE_APP_ID"],
  #       service_credentials_file: google_service_account_json_path,
  #       ipa_path: "../build/ios/Runner.ipa"
  #     )
  #   end
  # end
end
